package com.sxs.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxs.dao.EduSubjectDao;
import com.sxs.entity.EduSubject;
import com.sxs.entity.excel.SubjectData;
import com.sxs.entity.vo.SubjectVO;
import com.sxs.listener.SubjectExcelListener;
import com.sxs.service.EduSubjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 课程科目(EduSubject)表服务实现类
 *
 * @author makejava
 * @since 2021-09-27 16:49:37
 */
@Service("eduSubjectService")
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectDao, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file,EduSubjectService eduSubjectService) {
        try {
            InputStream inputStream=file.getInputStream();
            EasyExcel.read(inputStream, SubjectData.class,new SubjectExcelListener(eduSubjectService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<SubjectVO> listWithTree() {
        List<EduSubject> entities = list();
        //把EduSubject的数组entities包装成SubjectVO数组
        List<SubjectVO> subjectVOS = entities.stream().map(subject -> {
            SubjectVO subjectVO = new SubjectVO();
            BeanUtils.copyProperties(subject, subjectVO);
            return subjectVO;
        }).collect(Collectors.toList());
        //filter是java8的写法，取得所有parentId为0的数据，也就是一级目录
        //map也是java8的写法，用于封装数据，取得他的孩子（也就是下级目录）的数据
        List<SubjectVO> list = subjectVOS.stream().filter(subjectVO ->
                subjectVO.getParentId().equals("0")
        ).map((menu)->{
            menu.setChildren(getChildrenData(menu,subjectVOS));
            return menu;
        }).collect(Collectors.toList());
        return list;
    }

    @Override
    public EduSubject findById(String id) {
        return baseMapper.selectById(id);
    }

    private List<SubjectVO> getChildrenData(SubjectVO root, List<SubjectVO> all) {
        List<SubjectVO> children = all.stream().filter(subjectVO ->
                subjectVO.getParentId().equals(root.getId())
        ).map(subjectVO -> {
            subjectVO.setChildren(getChildrenData(subjectVO,all));
            return subjectVO;
        }).collect(Collectors.toList());
        return children;
    }
}
